<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="btnaddBrand">添加</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="桌面名" value="1"></el-option>
              <el-option label="包名" value="2"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- table -->
    <el-table stripe style="width: 100%" :data="browserTable" :key="key" border fit highlight-current-row ref="tableDataRef">
      <el-table-column v-if="colData[0].istrue" min-width="130" align="center" prop="name" label="launcher桌面"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="130" align="center" prop="package" label="包名"> </el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="250" align="center" prop="username" label="部署账号"></el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="250" align="center" prop="app_size" label="应用大小">
        <template slot-scope="scope">{{scope.row.app_size| zhDate}}</template>
      </el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="250" align="center" prop="app_version" label="版本号"></el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="140" align="center" prop="create_time" label="创建时间">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column min-width="80" align="center" prop="log" label="操作">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="compileControl(scope.row)">编辑</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <div>
      <el-dialog title="编辑" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false">
        <el-form :model="addForm" ref="ruleForm" :rules="rules" class="diolog_adapt">
          <div class="flex">
            <el-form-item label="桌面名称:" label-width="100px" prop="name" style="width:45%">
              <el-input v-model="addForm.name" placeholder="请输入桌面名称"></el-input>
            </el-form-item>
            <el-form-item label="桌面包名:" label-width="100px" prop="package" style="width:45%">
              <el-input v-model="addForm.package" placeholder="请输入桌面包名"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="应用文件:" label-width="100px" class="snElsx" prop="address">
          <div style="width:89%;display:flex" class="addPut">
            <el-input autocomplete="off" placeholder="请点击上传，上传apk件" style="flex:1" v-model="addForm.appUrl"></el-input>
            <!-- <el-upload :action="`${uploadLink}api/apkAdmin`" class="dlePut" style="right:10px" accept=".APK" :data="pdfData" :show-file-list="false" name="apk" :on-progress="beforeAvatarUpload" :on-success="apkSuccess">
              <el-button round size="mini">上传{{videoFlag ? '' : videoUploadPercent + '%'}}</el-button>
            </el-upload> -->
            <el-upload class="upload-demo dlePut" style="top:0;right:10px" action="#" id="file" :auto-upload="false" :show-file-list="false" :on-change="apkFile">
              <el-button class="" round size="mini">上传{{videoFlag ? '' : goodsData + '%'}}</el-button>
            </el-upload>
          </div>
        </el-form-item>
          <el-form-item label="关联账号" label-width="100px" prop="username">
            <!-- <el-input maxlength="100" show-word-limit autocomplete="off" placeholder="请输入关联账号" type="textarea" style="width:38%" v-model="addForm.username" :rows="2"></el-input> -->
            <el-select v-model="addForm.username" placeholder="请选择关联账号" multiple style="width:89%">
              <el-option v-for="item in lotoptions" :key="item.username" :label="item.username" :value="item.username"></el-option>
            </el-select>
          </el-form-item>
          <div class="flex flex-wrap" >
            <el-form-item label="背景图片:" label-width="100px" class="setting" prop="background" style="width:45%">
              <div class="flex felx_align logo_upload">
                <el-input v-model="addForm.background" placeholder="请上传图片"></el-input>
                <el-upload class="upload-demo" action :auto-upload="false" accept=".png,.jpg,.jpeg" :show-file-list="false" :on-change="compileapkAvatarUpload">
                  <el-button size="mini ">上传</el-button>
                </el-upload>
              </div>
            </el-form-item>
            <el-form-item label-width="100px" v-for="(domain, index) in addFormState.domains" :label="'控件' + (index+1)" :key="index" style="width:45%" class="setting">
              <div class="flex setting">
                <div class="flex felx_align logo_upload" style="width:80%">
                  <el-input v-model="domain.control_name" placeholder="请上传控件图片"></el-input>
                  <el-upload :action="`${uploadLink}api/uploadControl`" class="upload-demo" accept=".png,.jpg,.jpeg" :data="pdfData" :show-file-list="false" :on-success="handleSuccess">
                    <el-button size="mini " @click="controlP(index)">上传</el-button>
                  </el-upload>
                </div>
                <el-button @click.prevent="removeDomain(domain)" round>删除</el-button>
              </div>
            </el-form-item>
          </div>
          <el-form-item label-width="100px" v-if="editSubjects">
            <el-button @click="addDomain" size="mini" round>添加控件</el-button>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false" size="mini" round>取 消</el-button>
          <el-button v-if="editSubjects" type="primary" @click="getaddDesktop('ruleForm')" size="mini" round>确 定</el-button>
          <el-button v-else type="primary" @click="geteditDesktop('ruleForm')" size="mini" round>编辑</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import { queryDesktop, addDesktop, uploadBackground, uploadControl, desktopUsername, editDesktop } from "@/api/allocation.js";
import { ossupload, ossImage } from '@/utils/ossUpload.js'
import readMachine from 'app-info-parser'
import BMF from 'browser-md5-file'
import jszip from 'jszip'
import axios from 'axios'
import { mapState } from 'vuex'
export default {
  components: { dynamicTable },
  data() {
    return {
      checkboxVal: ["launcher桌面", "包名", "部署账号", "创建时间"],
      key: 1,
      colData: [], //动态控制table
      total: 0,
      searchTable: "",
      select: "", //搜索条件
      //归属table
      browserTable: [],
      //添加按钮控制
      dialogFormVisible: false,
      //编辑按钮控制
      editSubjects: true,
      //浏览器专题id
      subjectId: 0,
      //添加表单
      addForm: { name: "", package: "", control: [], background: "", username: "", appUrl: '', appVersion: '', appSize: '', app_name: '' },
      rules: {
        name: [{ required: true, message: "请输入桌面名称", trigger: "blur" }],
        package: [{ required: true, message: "请输入桌面包名", trigger: "blur" }],
        background: [{ required: true, message: "请上传图片", trigger: "blur" }],
        username: [{ required: true, message: "请输入关联账号", trigger: "blur" }]
      },
      addFormState: {
        domains: [{ control_addr: '', control_name: '' }]
      },
      pdfData: { userId: '', last_ip: '' },
      imgIndex: 0,
      //归属下拉选择
      lotoptions: [],
      listQuery: {
        startSize: 1,
        pageSize: 10,
        userId: localStorage.getItem("ID"),
        type: 1,
        name: undefined,
        package: undefined
      },
      //进度条
      videoUploadPercent: 0,
      videoFlag: true,
      uploadLink: process.env.VUE_APP_BASE_API
    }
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
    this.getqueryDesktop()
    this.pdfData.userId = localStorage.getItem("ID")
    this.pdfData.last_ip = sessionStorage.getItem("Ip")
    this.getdesktopUsername()
  },
  computed: {
    ...mapState({//获取上传滚动条
      goodsData: state => state.user.progress
    })
  },
  methods: {
    apkFile(event) {
      var filePath = event.name //文件名
      var index = filePath.lastIndexOf(".");
      var ext = filePath.substr(index + 1);
      this.addForm.appSize = event.size
      var supportFileTypes = ['ipa', 'apk', 'xapk'];
      var splits = (event.name || event).split('.');
      var fileType = splits[splits.length - 1].toLowerCase();
      if (!supportFileTypes.includes(fileType)) return this.$message.error('请上传正确的文件格式')
      const parser = new readMachine(event.raw)
      this.videoFlag = false;
      ossupload(event.raw, filePath, true, event.size).then(res => {
        this.videoFlag = true;
        this.addForm.appUrl = res
        this.$store.commit('user/SET_PROGRESS', 0)
        //文件类型
        if (ext == 'xapk') {//xapk
          this.getXapkInfo(parser);
        } else {
          parser.parse().then(res => {//apk
            this.addForm.package = res.package;
            this.addForm.appVersion = res.versionCode;
            this.addForm.app_name = (res.application.label).constructor == Array ? res.application.label[0] : res.application.label;
          }).catch(err => {
            this.$message.error('无法识别文件格式, 请重新上传')
          })
        }
      }).catch(err => {
        this.videoFlag = true;
        this.$store.commit('user/SET_PROGRESS', 0)
        err.code == 10086 ? this.$message(err.msg) : ''
        //上传oss失败关闭弹窗，4个异步任务，无法结束
        this.dialogFormVisible = false
      })
    },
    //获取xapk信息
    getXapkInfo(parser, type) {
      const xapk = parser
      let file = xapk.file;
      let blob = new Blob([file]);
      jszip.loadAsync(blob, { optimizedBinaryString: true }).then(res => {
        for (let key in res.files) {
          //判断是否是目录
          if (!res.files[key].dir) {
            //找到我们压缩包所需要的json文件
            if (/\.(json)$/.test(res.files[key].name)) {
              res.file(res.files[key].name).async('string').then(item => {
                //得到我们需要的JSON文件内容
                let infocontent = JSON.parse(item);
                this.addForm.package = infocontent.package_name;
                this.addForm.appVersion = infocontent.version_code;;
                this.addForm.app_name = infocontent.name;
              })
            }
          }
        }
      }).catch(err => {
        console.log('zpi失败', err)
      });
    },
    //apk上传
    beforeAvatarUpload() {
      this.apkUnplate = false;//将添加和上传的按钮分开
      this.videoFlag = false;
      if (Math.floor(event.percent) <= 99) {
        this.videoUploadPercent = Math.floor(event.percent)
      }
    },
    apkSuccess(res) {
      if (res.code == 200) {
        this.videoUploadPercent = 100;
        setTimeout(() => {
          this.videoUploadPercent = 0;
          this.videoFlag = true
          this.addForm.appUrl = res.data.filePath
          this.addForm.package = res.data.bg
          this.addForm.appVersion = res.data.versionCode
          this.addForm.appSize = res.data.size
          this.addForm.app_name = res.data.appName
        }, 500)
      } else {
        this.$message.error(res.msg)
        this.videoUploadPercent = 0;
        this.videoFlag = true
      }
    },
    //编辑
    geteditDesktop(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.control = this.addFormState.domains
          addForm.username = this.addForm.username.toString()
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.id = this.subjectId
          console.log("-------编辑参数", addForm)
          editDesktop(addForm).then(res => {
            this.$message.success(res.msg)
            this.getqueryDesktop()
            this.dialogFormVisible = false
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    compileControl(item) {
      console.log("-----------",item)
      this.editSubjects = false
      this.subjectId = item.id
      this.dialogFormVisible = true
      
      //查询渲染数据,item.control为null时for循环会报错
      let arr = item.control.map(item => {
        if(item != null) {
          return item
        }else {
          return { control_addr: '', control_name: '' }
        }
       })
       this.addFormState.domains = arr
      console.log('-----------',arr)
      this.addForm.username = item.username.split(',')
      this.addForm.name = item.name
      this.addForm.package = item.package
      this.addForm.background = item.background
      this.addForm.appUrl = item.app_url
      this.addForm.app_name = item.app_name
      this.addForm.appSize = item.app_size
       this.addForm.appVersion = item.app_version
    },
    //添加
    getaddDesktop(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // this.addForm.control = this.addFormState.domains.map(item => item.control_addr)
          this.addForm.control = this.addFormState.domains
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.username = this.addForm.username.toString()
          console.log("-------", addForm)
          addDesktop(addForm).then(res => {
            this.getqueryDesktop()
            this.$message.success(res.msg)
            this.dialogFormVisible = false
          })
        } else {
          return false
        }
      })
    },
    //背景图片上传
    compileapkAvatarUpload(file) {
      var fd = new FormData()
      fd.append('file', file.raw)
      fd.append('userId', localStorage.getItem("ID"))
      fd.append('last_ip', sessionStorage.getItem("Ip"))
      uploadBackground(fd).then(res => {
        this.addForm.background = res.data.imgPath
        console.log('图片', res.data)
      })
    },
    //控件图片上传
    handleSuccess(res) {
      if (res.code == 200) {
        this.addFormState.domains[this.imgIndex].control_addr = res.data.imgPath
        this.addFormState.domains[this.imgIndex].control_name = res.data.imgName
        console.log("-------------数据,",this.imgIndex, res,this.addFormState.domains)
      } else {
        this.$message.error(res.msg)
      }
    },
    controlP(index) {
      this.imgIndex = index
      //console.log("上传时触发", index)
    },
    //获取归属列表
    getdesktopUsername() {
      desktopUsername({ userId: localStorage.getItem("ID") }).then(res => {
        this.lotoptions = res.data
        console.log('----------111111',res.data)
      })
    },
    addDomain() {
      this.addFormState.domains.push({
        control_addr: '',
        control_name: '',
        key: Date.now()
      });
    },
    removeDomain(item) {
      var index = this.addFormState.domains.indexOf(item)
      if (index !== -1) {
        this.addFormState.domains.splice(index, 1)
      }
    },
    btnaddBrand() {
      this.editSubjects = true
      this.dialogFormVisible = true
    },
    getqueryDesktop(startSize = 1, pageSize = 10, type = 1, parameter) {
      queryDesktop(this.listQuery).then(res => {
        this.browserTable = res.data
        this.total = res.total
      }).catch(err => {
        this.browserTable = []
        this.total = 0
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getqueryDesktop();
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getqueryDesktop();
    },
    Refresh() {
      this.listQuery = {
        startSize: 1,
        pageSize: 10,
        userId: localStorage.getItem("ID"),
        type: 1,
        name: undefined,
        package: undefined
      }
      this.getqueryDesktop()
    },
    //搜索,1:桌面名，2：包名
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.type = 2
          this.listQuery.name = this.searchTable
          this.getqueryDesktop();
          break;
        case '2':
          this.listQuery.type = 3
          this.listQuery.package = this.searchTable
          this.getqueryDesktop();
          break;
      }
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.addForm = {
          name: "",
          package: "",
          control: [],
          background: "",
          username: "",
        }
        this.addFormState = { domains: [{ control_addr: '', control_name: '' }] }
      })
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.logo_upload {
  position: relative;
}
.upload-demo {
  position: absolute;
  right: 10px;
}
</style>